package eclipse.lib.sockets;
import eclipse.server.*;
import eclipse.server.threadpool.*;
import eclipse.util.*;
/**
 * Socket that represents a Server object.
 */
public class ServerSocket extends ThreadedTimer
{
	private java.net.ServerSocket server;
	private ClientSocket[] client;
	private int port;
	private int tmpCount = 0;
	private int ClientTimeout		= 0;
	/**
	 * Creates a new Server Socket
	 * @param iPort Port to listen on
	 * @param sckClient Array of ClientSockets that can be used
	 * @param timeout Client timeout value.
	 */
	public ServerSocket(int iPort, ClientSocket sckClient[], int timeout)
	{
		client = sckClient;
		port = iPort;
		setName("Server Thread");		
		setInterval(Database.NETPROCESSINTERVAL);		
		ClientTimeout = timeout;
		listen(); 				System.out.println("Listening...");
		start(); 				System.out.println("Loading server...");
		System.out.println("Server is ready");
	}	
	/** Begin listening */
	public void listen()
	{
		try 
		{
			server = new java.net.ServerSocket(port);			
			server.setSoTimeout(ClientTimeout);
			setEnabled(true);
		}
		catch (Exception e) 
		{
			eclipse.ErrorManager.handleError(e);
		}
	}
	public void tick()
	{

		for(tmpCount = 0; tmpCount < client.length; tmpCount++)
		{
			try
			{
				if(client[tmpCount] == null)
				{
					client[tmpCount] = new ClientSocket(server.accept());					
					System.out.println("Connected @" + tmpCount + ": " + client[tmpCount].getHost());
					Database.threadCache.process_NetThread[tmpCount] = new NetProcessThread(tmpCount);
				}						 						
			}
			catch(Exception e)
			{
				
			}
		}	
	}		
}
